<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>控制台主页</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
            background-color: #f5f5f5;
            color: #333;
        }
        
        .container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 0 15px;
        }
        
        .chart-row {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }
        
        .chart-col {
            flex: 1;
            min-width: 0;
        }
        
        .card {
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            overflow: hidden;
            height: 100%;
        }
        
        .card-header {
            background: #AA3130;
            color: #fff;
            padding: 15px 20px;
            font-size: 16px;
            font-weight: 500;
        }
        
        .card-body {
            padding: 20px;
        }
        
        .chart-container {
            width: 100%;
            height: 400px;
            position: relative;
        }
        
        .loading {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 400px;
            color: #666;
        }
        
        .error {
            color: #ff4d4f;
            text-align: center;
            padding: 20px;
        }
        
        @media (max-width: 768px) {
            .chart-row {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="chart-row">
            <div class="chart-col">
                <div class="card">
                    <div class="card-header">Token使用量统计</div>
                    <div class="card-body">
                        <div id="tokenChart" class="chart-container">
                            <div class="loading">加载中...</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="chart-col">
                <div class="card">
                    <div class="card-header">调用次数统计</div>
                    <div class="card-body">
                        <div id="callChart" class="chart-container">
                            <div class="loading">加载中...</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 引入本地ECharts -->
    <script th:src="@{/static/echarts/echarts.min.js}"></script>
    
    <script>
        // 全局变量
        let tokenChart = null;
        let callChart = null;
        
        // 初始化图表
        function initCharts() {
            if (typeof echarts === 'undefined') {
                showError('图表组件加载失败，请刷新页面重试');
                return;
            }
            
            // 初始化Token图表
            const tokenChartDom = document.getElementById('tokenChart');
            tokenChart = echarts.init(tokenChartDom);
            
            // 初始化调用次数图表
            const callChartDom = document.getElementById('callChart');
            callChart = echarts.init(callChartDom);
            
            // 加载数据
            loadTokenData();
            loadCallData();
        }
        
        // 加载Token使用数据
        async function loadTokenData() {
            try {
                const response = await fetch('/system/tokenStatistics/weeklyUsage');
                const result = await response.json();
                
                if (result.code === 0 || result.code === 200) {
                    renderTokenChart(result.data);
                } else {
                    showTokenError('获取数据失败: ' + (result.msg || '未知错误'));
                }
            } catch (error) {
                console.error('加载Token数据失败:', error);
                showTokenError('加载数据失败，请检查网络连接');
            }
        }
        
        // 加载调用次数数据
        async function loadCallData() {
            try {
                const response = await fetch('/system/tokenStatistics/weeklyCalls');
                const result = await response.json();
                
                if (result.code === 0 || result.code === 200) {
                    renderCallChart(result.data);
                } else {
                    showCallError('获取数据失败: ' + (result.msg || '未知错误'));
                }
            } catch (error) {
                console.error('加载调用次数数据失败:', error);
                showCallError('加载数据失败，请检查网络连接');
            }
        }
        
        // 渲染Token图表
        function renderTokenChart(data) {
            if (!tokenChart) return;
            
            const maxValue = Math.max(...data.values);
            
            const option = {
                title: {
                    text: data.isAdmin ? '所有用户近7天Token使用量' : '您近7天的Token使用量',
                    left: 'center',
                    textStyle: {
                        fontSize: 16,
                        fontWeight: 'normal'
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    },
                    formatter: function(params) {
                        return params[0].name + '<br/>' + 
                               'Token使用量: ' + params[0].value;
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: data.days,
                    axisTick: {
                        alignWithLabel: true
                    },
                    axisLabel: {
                        interval: 0,
                        rotate: data.days.length > 7 ? 30 : 0
                    }
                },
                yAxis: {
                    type: 'value',
                    name: 'Token使用量',
                    axisLabel: {
                        formatter: '{value}'
                    }
                },
                series: [{
                    name: 'Token使用量',
                    type: 'bar',
                    barWidth: '60%',
                    data: data.values.map(function(value, index) {
                        if (value === maxValue && maxValue > 0) {
                            return {
                                value: value,
                                itemStyle: {
                                    color: '#a90000'
                                }
                            };
                        }
                        return {
                            value: value,
                            itemStyle: {
                                color: '#5470c6'
                            }
                        };
                    }),
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}'
                    }
                }]
            };
            
            tokenChart.setOption(option);
        }
        
        // 渲染调用次数图表
        function renderCallChart(data) {
            if (!callChart) return;
            
            const maxValue = Math.max(...data.values);
            
            const option = {
                title: {
                    text: data.isAdmin ? '所有用户近7天调用次数' : '您近7天的调用次数',
                    left: 'center',
                    textStyle: {
                        fontSize: 16,
                        fontWeight: 'normal'
                    }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow'
                    },
                    formatter: function(params) {
                        return params[0].name + '<br/>' + 
                               '调用次数: ' + params[0].value;
                    }
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: data.days,
                    axisTick: {
                        alignWithLabel: true
                    },
                    axisLabel: {
                        interval: 0,
                        rotate: data.days.length > 7 ? 30 : 0
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '调用次数',
                    axisLabel: {
                        formatter: '{value}'
                    }
                },
                series: [{
                    name: '调用次数',
                    type: 'bar',
                    barWidth: '60%',
                    data: data.values.map(function(value, index) {
                        if (value === maxValue && maxValue > 0) {
                            return {
                                value: value,
                                itemStyle: {
                                    color: '#a90000'
                                }
                            };
                        }
                        return {
                            value: value,
                            itemStyle: {
                                color: '#91cc75'
                            }
                        };
                    }),
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}'
                    }
                }]
            };
            
            callChart.setOption(option);
        }
        
        // 显示Token图表错误信息
        function showTokenError(message) {
            const chartDom = document.getElementById('tokenChart');
            chartDom.innerHTML = `<div class="error">${message}</div>`;
        }
        
        // 显示调用次数图表错误信息
        function showCallError(message) {
            const chartDom = document.getElementById('callChart');
            chartDom.innerHTML = `<div class="error">${message}</div>`;
        }
        
        // 响应式处理
        window.addEventListener('resize', function() {
            if (tokenChart) {
                tokenChart.resize();
            }
            if (callChart) {
                callChart.resize();
            }
        });
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            initCharts();
        });
    </script>
</body>
</html>

